﻿using System;
using System.Web.Mvc;
using CharacterCreation.Business.Repositories;

namespace CharacterCreation.Business.Controllers {
    public class BaseController<ViewModel> : Controller where ViewModel : new() {
        protected IRepository<ViewModel> repository = RepositoryFactory.Create<ViewModel>();

        public virtual ActionResult Index() {
            return View(repository.Get());
        }

        public virtual ActionResult Create() {
            ViewData["IsValid"] = true;
            ViewModel entity = new ViewModel();
            return View(entity);
        }

        [HttpPost]
        [ValidateInput(false)]
        public virtual ActionResult Create(ViewModel entity) {
            ViewData["IsValid"] = ModelState.IsValid;

            if (ModelState.IsValid)
            {
                repository.Add(entity);
                return RedirectToAction("Index");
            }
            else
            {
                return View(entity);
            }
        }

        public virtual ActionResult Delete(Guid id) {
            repository.Delete(id);
            return RedirectToAction("Index");
        }

        public virtual ActionResult Edit(Guid id) {
            ViewData["IsValid"] = true;
            ViewModel entity = repository.Get(id);
            return View(entity);
        }

        [HttpPost]
        [ValidateInput(false)]
        public virtual ActionResult Edit(ViewModel entity) {
            ViewData["IsValid"] = ModelState.IsValid;

            if (ModelState.IsValid)
            {
                repository.Update(entity);
                return RedirectToAction("Index");
            }
            else
            {
                return View(entity);
            }
        }

    }
}
